package vaccine.appointment.system.inventory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vaccine.appointment.system.common.enums.DelFlgEnum;
import vaccine.appointment.system.common.exception.CommonException;
import vaccine.appointment.system.inventory.dataobject.Inventory;
import vaccine.appointment.system.inventory.errorcode.InventoryErrorCode;
import vaccine.appointment.system.inventory.mapper.InventoryMapper;
import vaccine.appointment.system.inventory.mq.LowInventoryCapacityMessage;
import vaccine.appointment.system.inventory.service.InventoryService;
import vaccine.appointment.system.inventory.vo.AddInventoryRequest;
import vaccine.appointment.system.inventory.vo.InventoryVO;
import vaccine.appointment.system.inventory.vo.LowStockAlertVO;
import vaccine.appointment.system.user.dataobject.User;
import vaccine.appointment.system.user.enums.IdentityInfoEnum;
import vaccine.appointment.system.user.mapper.UserMapper;
import vaccine.appointment.system.vaccine.dataobject.Vaccine;
import vaccine.appointment.system.vaccine.enums.VaccineTypeEnum;
import vaccine.appointment.system.vaccine.mapper.VaccineMapper;
import vaccine.appointment.system.vaccinationsite.dataobject.VaccinationSite;
import vaccine.appointment.system.vaccinationsite.mapper.VaccinationSiteMapper;

import java.util.ArrayList;
import java.util.List;

/**
 * 库存服务实现类
 */
@Service
public class InventoryServiceImpl implements InventoryService {

    private static final int DEFAULT_LOW_STOCK_THRESHOLD = 10;

    @Autowired
    private InventoryMapper inventoryMapper;

    @Autowired
    private VaccineMapper vaccineMapper;

    @Autowired
    private VaccinationSiteMapper vaccinationSiteMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Boolean add(Inventory inventory) {
        inventoryMapper.insert(inventory);
        return true;
    }

    @Override
    public Boolean delete(Integer id) {
        Inventory inventory = inventoryMapper.selectById(id);
        if (inventory == null || inventory.getDelFlg().equals(DelFlgEnum.DELETED.getCode())) {
            return false;
        }
        inventory.setDelFlg(DelFlgEnum.DELETED.getCode());
        inventoryMapper.updateById(inventory);
        return true;
    }

    @Override
    public Boolean update(Inventory inventory) {
        inventoryMapper.updateById(inventory);
        return true;
    }

    @Override
    public Inventory selectById(Integer id) {
        return inventoryMapper.selectById(id);
    }

    @Override
    public void sendMessge(LowInventoryCapacityMessage message) {
        //发送mq
        // TODO: 实现RabbitMQ消息发送逻辑
    }

    /**
     * 添加库存记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addInventory(AddInventoryRequest request, Integer userId) {
        // 1. 获取当前用户信息，确定接种点ID
        User user = userMapper.selectById(userId);
        if (user == null || user.getDelFlg().equals(DelFlgEnum.DELETED.getCode())) {
            throw new CommonException(InventoryErrorCode.NOT_FOUND);
        }

        // 2. 确定接种点ID（接种点管理员使用自己的接种点，超级管理员使用请求中的接种点）
        Integer vaccinationSiteId;
        if (user.getIdentityInfo().equals(IdentityInfoEnum.HOSPITAL_ADMIN.getCode())) {
            // 接种点管理员只能管理自己的接种点
            vaccinationSiteId = user.getVaccinationSiteId();
            if (vaccinationSiteId == null) {
                throw new CommonException(InventoryErrorCode.INVENTORY_NOT_AUTHORIZED);
            }
        } else {
            // 超级管理员可以指定接种点
            vaccinationSiteId = request.getVaccinationSiteId();
            if (vaccinationSiteId == null) {
                throw new CommonException(InventoryErrorCode.INVALID_PARAMETER);
            }
        }

        // 3. 验证疫苗是否存在
        Vaccine vaccine = vaccineMapper.selectById(request.getVaccineId());
        if (vaccine == null || vaccine.getDelFlg().equals(DelFlgEnum.DELETED.getCode())) {
            throw new CommonException(InventoryErrorCode.INVENTORY_NOT_FOUND);
        }

        // 4. 验证接种点是否存在
        VaccinationSite site = vaccinationSiteMapper.selectById(vaccinationSiteId);
        if (site == null || site.getDelFlg().equals(DelFlgEnum.DELETED.getCode())) {
            throw new CommonException(InventoryErrorCode.INVENTORY_NOT_FOUND);
        }

        // 5. 检查该接种点的该疫苗库存是否已存在
        QueryWrapper<Inventory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vaccine_id", request.getVaccineId());
        queryWrapper.eq("vaccination_site_id", vaccinationSiteId);
        queryWrapper.eq("del_flg", DelFlgEnum.NOT_DELETED.getCode());
        Inventory existingInventory = inventoryMapper.selectOne(queryWrapper);

        if (existingInventory != null) {
            throw new CommonException(InventoryErrorCode.INVENTORY_ALREADY_EXISTS);
        }

        // 6. 创建库存记录
        Inventory inventory = new Inventory();
        inventory.setVaccineId(request.getVaccineId());
        inventory.setVaccinationSiteId(vaccinationSiteId);
        inventory.setCount(request.getCount());
        inventory.setDelFlg(DelFlgEnum.NOT_DELETED.getCode());

        inventoryMapper.insert(inventory);
        return true;
    }

    /**
     * 更新库存数量
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateInventoryCount(Integer inventoryId, Integer changeCount, Integer userId) {
        // 1. 查询库存记录
        Inventory inventory = inventoryMapper.selectById(inventoryId);
        if (inventory == null || inventory.getDelFlg().equals(DelFlgEnum.DELETED.getCode())) {
            throw new CommonException(InventoryErrorCode.INVENTORY_NOT_FOUND);
        }

        // 2. 计算新库存
        Integer newCount = inventory.getCount() + changeCount;
        if (newCount < 0) {
            throw new CommonException(InventoryErrorCode.INVALID_STOCK_COUNT);
        }

        // 3. 更新库存
        inventory.setCount(newCount);
        inventoryMapper.updateById(inventory);

        return true;
    }

    /**
     * 查询接种点的库存列表
     */
    @Override
    public List<InventoryVO> getInventoryList(Integer vaccinationSiteId) {
        QueryWrapper<Inventory> queryWrapper = new QueryWrapper<>();
        if (vaccinationSiteId != null) {
            queryWrapper.eq("vaccination_site_id", vaccinationSiteId);
        }
        queryWrapper.eq("del_flg", DelFlgEnum.NOT_DELETED.getCode());
        queryWrapper.orderByDesc("id");

        List<Inventory> inventoryList = inventoryMapper.selectList(queryWrapper);
        List<InventoryVO> voList = new ArrayList<>();

        for (Inventory inventory : inventoryList) {
            InventoryVO vo = new InventoryVO();
            vo.setId(inventory.getId());
            vo.setVaccineId(inventory.getVaccineId());
            vo.setVaccinationSiteId(inventory.getVaccinationSiteId());
            int stockCount = inventory.getCount() == null ? 0 : inventory.getCount();
            vo.setCount(stockCount);
            vo.setQuantity(stockCount);
            vo.setLowStockThreshold(DEFAULT_LOW_STOCK_THRESHOLD);

            // 查询疫苗信息（只有当vaccineId不为null时才查询）
            if (inventory.getVaccineId() != null) {
                Vaccine vaccine = vaccineMapper.selectById(inventory.getVaccineId());
                if (vaccine != null) {
                    vo.setVaccineName(vaccine.getName());
                    vo.setVaccineType(VaccineTypeEnum.getDescByCode(vaccine.getType()));
                    vo.setProductionDate(vaccine.getProductionDate());
                    vo.setExpirationDate(vaccine.getValidityPeriod());
                } else {
                    // 疫苗不存在，设置默认值
                    vo.setVaccineName("未知疫苗");
                    vo.setVaccineType("-");
                }
            } else {
                // vaccineId为null，设置默认值
                vo.setVaccineName("未关联疫苗");
                vo.setVaccineType("-");
            }

            // 查询接种点信息
            VaccinationSite site = vaccinationSiteMapper.selectById(inventory.getVaccinationSiteId());
            if (site != null) {
                vo.setVaccinationSiteName(site.getName());
            }
            vo.setIsLowStock(stockCount < vo.getLowStockThreshold());

            voList.add(vo);
        }

        return voList;
    }

    /**
     * 查询低库存预警列表
     */
    @Override
    public List<LowStockAlertVO> getLowStockAlerts(Integer vaccinationSiteId, Integer threshold) {
        if (threshold == null) {
            threshold = 10;
        }

        QueryWrapper<Inventory> queryWrapper = new QueryWrapper<>();
        if (vaccinationSiteId != null) {
            queryWrapper.eq("vaccination_site_id", vaccinationSiteId);
        }
        queryWrapper.le("count", threshold);
        queryWrapper.eq("del_flg", DelFlgEnum.NOT_DELETED.getCode());
        queryWrapper.orderByAsc("count");

        List<Inventory> inventoryList = inventoryMapper.selectList(queryWrapper);
        List<LowStockAlertVO> voList = new ArrayList<>();

        for (Inventory inventory : inventoryList) {
            LowStockAlertVO vo = new LowStockAlertVO();
            vo.setId(inventory.getId());
            vo.setVaccineId(inventory.getVaccineId());
            vo.setVaccinationSiteId(inventory.getVaccinationSiteId());
            vo.setCount(inventory.getCount());

            // 设置预警级别
            if (inventory.getCount() <= 5) {
                vo.setAlertLevel(2); // 严重低库存
            } else {
                vo.setAlertLevel(1); // 低库存
            }

            // 查询疫苗信息（只有当vaccineId不为null时才查询）
            if (inventory.getVaccineId() != null) {
                Vaccine vaccine = vaccineMapper.selectById(inventory.getVaccineId());
                if (vaccine != null) {
                    vo.setVaccineName(vaccine.getName());
                    vo.setVaccineType(vaccine.getType());
                } else {
                    vo.setVaccineName("未知疫苗");
                    vo.setVaccineType(null);
                }
            } else {
                vo.setVaccineName("未关联疫苗");
                vo.setVaccineType(null);
            }

            // 查询接种点信息
            VaccinationSite site = vaccinationSiteMapper.selectById(inventory.getVaccinationSiteId());
            if (site != null) {
                vo.setVaccinationSiteName(site.getName());
            }

            voList.add(vo);
        }

        return voList;
    }

    /**
     * 根据疫苗ID和接种点ID查询库存
     */
    @Override
    public Inventory getByVaccineAndSite(Integer vaccineId, Integer vaccinationSiteId) {
        QueryWrapper<Inventory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vaccine_id", vaccineId);
        queryWrapper.eq("vaccination_site_id", vaccinationSiteId);
        queryWrapper.eq("del_flg", DelFlgEnum.NOT_DELETED.getCode());
        return inventoryMapper.selectOne(queryWrapper);
    }
}
